import workApi from '@/api/tjzy/work/workApi'
import router from '@/router'
import { message, Modal } from 'ant-design-vue'
import modalUtil from '@/utils/ModalUtil'
import tool from '@/utils/tool'
import callApi from '@/api/tjzy/call/callApi'
import predictCallApi from '@/api/tjzy/call/predict/predictCallApi'
import phoneComplaintApi from '@/api/tjzy/phone/complaint/phoneComplaintApi'
import { sensitivePhone } from '@/utils/sensitiveUtil'
import { isSentive } from '@/utils/permission'

const htWebCallLoaded = ref(false)
const htWebCallInstance = ref()
const htCallResult = ref()
//主叫号码集合
const callerNumberList = ref([])
//坐席当前状态
const agentCurrentStatus = ref()
//当前通话或者来电的手机号密文
const secretPhone = ref()
//当前正在通话的手机号，中间四位脱敏
const callingPhone = ref()
console.log('isSentive', isSentive())

const showCallingPhone = ref()
const callId = ref()
//是否通话中
const isCalling = ref(false)
//是否通话保持中
const isKeep = ref(false)
//是否静音中
const isMute = ref(false)
//是否振铃中
const isRinging = ref(false)
//是否监听中
const isMonitor = ref(false)
const isConn = ref(false)
const customerInfo = ref()
const htAccount = ref()
const workId = ref()

const createHtCall = () => {
	if (!htWebCallLoaded.value || !htWebCallInstance.value || !htWebCallInstance.value.CreateHtrxCall) {
		throw new Error('HtrxWebCall or CreateHtrxCall is not available')
	}
	const options = createHtCallWrapper()
	htCallResult.value = htWebCallInstance.value.CreateHtrxCall(options)
	//登录事件
	loginCallEvent()
	//是否连接
	checkConn()
	//拨打是否成功
	makeCallEvent()
	//呼入事件
	incomingCallEvent()
	//接听事件
	answerCallEvent()
	//挂断事件
	disconnectedCallEvent()
	//坐席状态事件
	agentStatusEvent()
	//磋商事件
	consultCallEvent()
	//监听事件
	monitorCallEvent()
}

const createHtCallWrapper = () => {
	const options = {
		initurl: 'https://saas-cti.htrxcall.com/agentmanage/',
		ringurl: '/video/ring.mp3',
		hangupringurl: '/video/hangup.mp3',
		passurl: '/video/du.mp3',
		callingurl: '/video/calling.mp3',
		reconnect: true, //是否断线重连
		call_expires: 30, //外呼超时挂机时间（秒）
		newtab: false, //开启新页签执行事件
		workerurl: 'worker.js', //newtab 为 true 时，设置新页签共享
		debug: true,
		error: function (e) {
			console.log(e)
			if (e.code === 1003) {
				modalUtil.error('【账号SDK登录失败】账号开通未完成或密码已变更，请联系郭浩楠重置账号信息！')
			} else if (e.code === 1000 || e.code === 1001) {
				modalUtil.error('【麦克风权限异常】请按操作手册配置麦克风权限并重启浏览器，重启浏览器后当前提示即可消失！')
			} else {
				modalUtil.error(e)
			}
		},
		success: function () {
			htCallResult.value.config.IsAutoAnswer = false
			loginCall()
		},
		close: function () {
			modalUtil.error('【账号下线】可能是他人正在登录您的账号或者账号权限正在变更，刷新浏览器即可恢复')
		}
	}
	console.log('createHtCallWrapper - ', options)
	return options
}

const checkConn = () => {
	setInterval(() => {
		isConn.value = htCallResult.value.actions.checkConn()
	}, 500)
}

const loginCall = () => {
	//检查是否连接，有连接就执行登录
	if (htCallResult.value.actions.checkConn()) {
		const account = tool.data.get('USER_INFO').account
		htCallResult.value.actions.login(account, account)
		htAccount.value = account
		callerNumberList.value = htCallResult.value.actions.getZCallerList()
		console.log('主叫号码：', callerNumberList.value)
		callerNumberList.value.forEach((item) => {
			item.ZCallerName = item.ZCallerName.replace('预外呼', '智能路由')
		})
	}
}

const logoutCall = () => {
	console.log('logoutCall')
	htCallResult.value.actions.loginout()
}

const loadHtWebCallScript = () => {
	if (tool.data.get('USER_INFO').roleCodeList.includes('mediator')) {
		console.log('初始化')
		if (htWebCallLoaded.value) {
			createHtCall()
			return
		}
		console.log('开始加载恒天SDK')
		const script = document.createElement('script')
		script.src = '/js/htrxcallwhole.min.js'
		script.onload = () => {
			if (window.HtrxWebCall) {
				htWebCallInstance.value = window.HtrxWebCall
				htWebCallLoaded.value = true
				createHtCall()
			} else {
				console.error('HtrxWebCall is not defined on window')
			}
		}
		script.onerror = (error) => {
			console.error('Failed to load HtrxWebCall script:', error)
		}
		document.head.appendChild(script)
		console.log('加载恒天SDK结束')
	}
}

/**
 * 修改坐席状态
 * @param status
 */
const changeAgentCurrentStatus = (status) => {
	console.log('修改坐席状态：' + status)
	htCallResult.value.actions.selChange(status)
}

/**
 * 单点外呼
 * @param phoneNumber
 * @param business
 */
const singlePointCall = (phoneNumber, business) => {
	console.log('点击拨打的时候传过来的值：', business)
	if (htCallResult.value === undefined) {
		Modal.error({
			title: '提示：',
			okText: '确定',
			content: htAccount.value + '：SDK登录失败，刷新浏览器',
			onOk: () => {}
		})
		return
	}
	callApi.getCallNumber().then((res: any) => {
		if (res == null || res.length === 0) {
			alert('请先设置主叫号码')
			return
		}
		const param = {
			phone: phoneNumber,
			business: business.caseId,
			hasencrypt: false,
			type: 0,
			zcaller: res,
			callBackUrl: 'http://117.72.13.165:9003/api/bizapp/tjzy/ht/callback/record'
		}
		console.log('主叫号码：', res)
		console.log('主叫-线路：', callerNumberList)
		let lineName = ''
		//遍历callerNumberList，获取选中 res 对应的线路名称
		const selectedCaller = callerNumberList.value.find((item) => item.ZCaller === res)
		if (selectedCaller) {
			lineName = selectedCaller.ZCallerName
		}
		//三方线路不校验黑名单
		if (lineName && !lineName.includes('三方')) {
			//黑名单校验——旧
			// console.log('是三方线路 - ', business)
			// //校验号码库黑名单，通过之后才能拨打
			// blacklist.verifyBlack(phoneNumber).then((r) => {
			// 	console.log('号码库黑名单 - ', r)
			// 	if (r && r[0] && r[0].forbid === 1) {
			// 		message.error('黑名单用户禁止呼叫')
			// 	} else {
			// 		//黑名单校验通过了才能继续拨打电话
			// 		htCallResult.value.actions.call(param)
			// 		workId.value = business.workId
			// 		isRinging.value = true
			// 		// callingPhone.value = phoneNumber
			// 		callingPhone.value = isSentive() ? sensitivePhone(phoneNumber) : phoneNumber
			// 	}
			// })
			//黑名单投诉用户校验——新
			phoneComplaintApi.verifyComplaint(phoneNumber).then((res: any) => {
				if (res && res[0] && res[0].type === 1) {
					message.error('黑名单投诉用户禁止使用自营线路呼叫')
				} else {
					//黑名单校验通过了才能继续拨打电话
					htCallResult.value.actions.call(param)
					workId.value = business.workId
					isRinging.value = true
					// callingPhone.value = phoneNumber
					callingPhone.value = isSentive() ? sensitivePhone(phoneNumber) : phoneNumber
				}
			})
		} else {
			//走之前的逻辑
			htCallResult.value.actions.call(param)
			workId.value = business.workId
			isRinging.value = true
			// callingPhone.value = phoneNumber
			// callingPhone.value = sensitivePhone(phoneNumber)
			callingPhone.value = isSentive() ? sensitivePhone(phoneNumber) : phoneNumber
		}
	})
}

/**
 * 接听方法
 */
const answerCall = () => {
	htCallResult.value.actions.answer()
}

/**
 * 主动挂断电话方法
 */
const disconnectedCall = () => {
	console.log('坐席主动挂断电话')
	htCallResult.value.actions.hangup()
}

/**
 * 转内呼
 */
const internalCall = (htAccount) => {
	console.log('内呼')
	htCallResult.value.actions.internalcall(htAccount, null)
}

/**
 * 磋商
 * @param htAccount
 * @param caseId
 */
const consultCall = (htAccount) => {
	const param = { type: 'PHONE', workid: htAccount }
	htCallResult.value.actions.consult(param)
}

/**
 * 磋商
 * @param htAccount
 * @param caseId
 */
const meetingCall = () => {
	console.log('会议')
	htCallResult.value.actions.conference()
}

/**
 * 接回
 */
const transferMeCall = () => {
	htCallResult.value.actions.transferme()
}

/**
 * 转接
 */
const transferCall = () => {
	htCallResult.value.actions.transfer()
}

/**
 *通话保持
 */
const keepCall = () => {
	console.log('电话保持')
	htCallResult.value.actions.holdcall()
	isKeep.value = true
}

/**
 *取消通话保持
 */
const reKeepCall = () => {
	console.log('取消电话保持')
	htCallResult.value.actions.reholdcall()
	isKeep.value = false
}

/**
 *通话静音
 */
const muteCall = () => {
	if (isCalling.value) {
		console.log('电话静音')
		htCallResult.value.actions.mute()
		isMute.value = true
	}
}

/**
 *取消通话静音
 */
const reMuteCall = () => {
	if (isMute.value) {
		console.log('取消电话静音')
		htCallResult.value.actions.remute()
		isMute.value = false
	}
}

const monitorCall = (agentNum) => {
	htCallResult.value.actions.monitor(agentNum, '')
}

const reMonitorCall = () => {
	htCallResult.value.actions.stopmonitor()
	isMonitor.value = false
}

const forcedCall = (agentNum) => {
	htCallResult.value.actions.forcedrelease(agentNum, '')
}

function loginCallEvent() {
	htCallResult.value.events.EventLogin = function (data) {
		console.log('登录是否成功')
		console.log(data)
		if (data.EventCode === 200) {
			callApi.startListen(data.ResultMsg.PhoneNo)
		}
	}
}

/**
 * 拨打是否成功
 */
function makeCallEvent() {
	htCallResult.value.events.EventMakeCall = function (data) {
		console.log('拨打是否成功')
		console.log(data)
		if (!data.Result) {
			modalUtil.error('外呼失败')
		}
		callId.value = data.ResultMsg.CallId
	}
}

/**
 * 呼入
 */
const incomingCallEvent = () => {
	htCallResult.value.events.EventComeCall = function (data) {
		// console.log('呼入')
		// console.log(data)
		isRinging.value = true
		callingPhone.value = isSentive() ? sensitivePhone(data.ResultMsg.CallPhone) : data.ResultMsg.CallPhone
		// callingPhone.value = data.ResultMsg.CallPhone
		secretPhone.value = data.ResultMsg.SecretPhone
		if (data.ResultMsg.CallingType == 'Predict') {
			console.log('预测外呼来电，自动接听')
			answerCall()
			//黑名单投诉用户校验
			phoneComplaintApi.verifyComplaint(data.ResultMsg.CallPhone).then((res: any) => {
				if (res && res[0] && res[0].type === 1) {
					message.warn('当前接听手机号为投诉手机号，请谨慎沟通！！！')
				}
			})
			//查询透传数据
			predictCallApi.getCallDetailById(data.ResultMsg.BussParam).then((res) => {
				if (res.customerInfo) {
					customerInfo.value = res.customerInfo
				}
				if (res.caseId !== null) {
					workApi
						.autoAddByCaseId({
							caseId: res.caseId,
							liaisonPhone: data.ResultMsg.CallPhone
						})
						.then((workRes: any) => {
							router.push({
								path: '/tjzy/case/detail/' + res.caseId,
								query: {
									caseId: res.caseId,
									debtorName: workRes.debtorName,
									sort: 'descending',
									cleanLoanAmount: workRes.cleanLoanAmount
								}
							})
						})
				}
			})
		}
		//正常来电
		if (data.ResultMsg.CallingType == 'Normal') {
			modalUtil.confirm(
				'您有新的来电,来电号码：' + data.ResultMsg.CallPhone + ' 是否接听？',
				'接听',
				'挂断',
				() => {
					answerCall()
				},
				() => {
					disconnectedCall()
				}
			)
		}
		if (data.ResultMsg.CallingType == 'InternalCall') {
			console.log('内呼来电')
		}
		//磋商来电
		if (data.ResultMsg.CallingType == 'Negotiation') {
			modalUtil.confirm(
				'磋商来电',
				'接听',
				'挂断',
				() => {
					answerCall()
				},
				() => {
					disconnectedCall()
				}
			)
		}
	}
}

/**
 * 接听事件
 */
const answerCallEvent = () => {
	htCallResult.value.events.EventCallIng = function (data) {
		console.log('接听事件')
		console.log(data)
		callApi.setCallUser(data.ResultMsg.CallId)
		audio('/video/calling.mp3')
		isRinging.value = false
		isCalling.value = true
	}
}

/**
 * 挂断事件
 */
const disconnectedCallEvent = () => {
	htCallResult.value.events.EventHangup = function (data) {
		console.log('挂断事件')
		console.log(data)
		audio('/video/hangup.mp3')
		if (data.ResultMsg.asrResultName === '已接听') {
			console.log('接听后挂断')
		} else {
			console.log('无人接听')
			if (workId.value != null) {
				workApi.editWork({ id: workId.value, workResult: 2 })
			}
		}
		isCalling.value = false
		isRinging.value = false
	}
}

/**
 * 坐席切换状态事件
 */
const agentStatusEvent = () => {
	htCallResult.value.events.EventState = function (data) {
		console.log('坐席状态' + data.ResultMsg)
		agentCurrentStatus.value = data.ResultMsg
	}
}

/**
 * 磋商事件
 */
const consultCallEvent = () => {
	htCallResult.value.events.EventConsultation = function (data) {
		if (data.Result) {
			message.success('磋商成功')
		} else {
			message.error(data.ResultMsg)
		}
	}
}

const monitorCallEvent = () => {
	htCallResult.value.events.EventMonitor = function (data) {
		if (data.Result) {
			isMonitor.value = true
		} else {
			modalUtil.error(data.ResultMsg)
		}
	}
}

const audio = (url) => {
	const videoElement = document.createElement('video')
	videoElement.src = url
	// 播放视频
	videoElement.play()
}

export default {
	loadHtWebCallScript,
	logoutCall,
	changeAgentCurrentStatus,
	singlePointCall,
	answerCall,
	disconnectedCall,
	keepCall,
	reKeepCall,
	muteCall,
	reMuteCall,
	consultCall,
	meetingCall,
	monitorCall,
	reMonitorCall,
	forcedCall,
	transferCall,
	transferMeCall,
	showCallingPhone,
	htCallResult,
	callerNumberList,
	agentCurrentStatus,
	secretPhone,
	isConn,
	callingPhone,
	customerInfo,
	callId,
	isCalling,
	isKeep,
	isMute,
	isMonitor,
	isRinging
}
